package netty.tcpbug.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author Huhailong
 * @Description 通过netty实现时间服务器
 * @Date 2021/4/12.
 */
public class TimeServer {

    public void bind(int port) throws InterruptedException {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(); //用于接受客户端请求
        EventLoopGroup workerGroup = new NioEventLoopGroup();   //用于处理客户端请求
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();    //服务端辅助启动类
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)  //这只创建的channel为NioServerSocketChannel,对应nio中的ServerSocketCHannel
                    .option(ChannelOption.SO_BACKLOG,1024)  //设置TCP参数，此处将backlog设置为1024
                    .childHandler(new ChildChannelHandler());   //绑定I/O事件处理类ChildChannelHandler类，主要作用类似于Reactor中的handler类，主要用于处理网络I/O事件
            //绑定端口，同步等待成功
            ChannelFuture future = serverBootstrap.bind(port).sync();  //future用于异步操作的通知和回调
            System.out.println("The time server is start in port : "+port);
            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
            System.out.println("close time server");
        }finally {
            //优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
            socketChannel.pipeline().addLast(new StringDecoder());
            socketChannel.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        new TimeServer().bind(port);
    }
}
